package cc.czlee.cloud.zuul.filters;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

/*
 * Create by Colbert on 2019-05-02
 *
 * Copyright (C) 2019 chuanzhigo@gmail.com.
 */

/**
 * 前置过滤器
 */
@Component
@RefreshScope
public class PreFilter extends ZuulFilter {
    private Logger logger = LoggerFactory.getLogger(PreFilter.class);

    /**
     * 这里注入config中的token的值
     *
     * 默认不刷新，当配置文件变更需要重启当前项目重新读取
     *
     * 需要添加 actuator 依赖，配置 @RefreshScope 注解，POST 访问 http://localhost:8700/actuator/refresh 手动刷新
     */
    @Value("${token}")
    private boolean token;

    @Override
    public String filterType() {
        // pre -> route -> post error
        // return "pre";
        /*
         * 过滤器类型
         */
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        /*
         * 优先级，在本类型内数值越小，优先级越高
         */
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        /*
         * 是否过滤
         */
        return true;
    }


    @Override
    public Object run() throws ZuulException {
        logger.warn("pre filter run");
        if (token) {
            // 当前请求信息
            RequestContext requestContext = RequestContext.getCurrentContext();
            HttpServletRequest request = requestContext.getRequest();
            // 获取token请求头,验证是否登录
            String token = request.getHeader("token");
            if (StringUtils.isEmpty(token)) {
                // 设置是否继续进行路由转发
                requestContext.setSendZuulResponse(false);
                requestContext.setResponseStatusCode(401);
                requestContext.setResponseBody("{\"msg\": \"401, access without token!\"}");
            }
        }
        // 可以使用该方法向别的过滤器传递参数
        //requestContext.set(key, value);
        // 返回值没有意义
        return null;
    }
}
